/**
 * 
 */
package com.csc.bankingsystem.core.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csc.bankingsystem.core.dao.UserInfoDAO;
import com.csc.bankingsystem.core.entity.HistoryRecord;
import com.csc.bankingsystem.core.entity.UserInfo;
import com.csc.bankingsystem.core.entity.UserInfoRole;
import com.csc.bankingsystem.core.enumeration.HistoryRecordActionEnum;
import com.csc.bankingsystem.core.service.HistoryRecordService;
import com.csc.bankingsystem.core.service.UserInfoService;
import com.csc.bankingsystem.core.util.CustomHibernateDaoSupport;


/**
 * Implement all service operation of UserInfoService
 * @author angelkid
 *
 */
@Service("userInfoService")
@Transactional
public class UserInfoServiceImpl extends CustomHibernateDaoSupport implements UserInfoService {

	@Autowired
	UserInfoDAO userInfoDAO;
	
	@Autowired
	HistoryRecordService historyRecordService;
	
	@Transactional(readOnly=true)
	public UserInfo find(long id) {
		return userInfoDAO.find(id);
	}

	public List<UserInfo> findAll() {
		return userInfoDAO.findAll();
	}

	public Long countAll() {
		return userInfoDAO.countAll();
	}

	public Long save(UserInfo userInfo){
		return userInfoDAO.save(userInfo);
	}

	public void update(UserInfo userInfo){
		userInfoDAO.update(userInfo);
	}

	public void delete(UserInfo userInfo) {
		userInfoDAO.delete(userInfo);
	}
	
	public UserInfo getUserInfoByLoginId(String loginId){
		return userInfoDAO.getUserInfoByLoginId(loginId);
	}
	
	public List<UserInfoRole> getUserInfoRoleByLoginId(String loginId){
		UserInfo userInfo = userInfoDAO.getUserInfoByLoginId(loginId);
		
		return (userInfo == null)?null:userInfo.getUserInfoRoles();
	}
	
	public void updateByUserObject(UserInfo obj){
		UserInfo userInfo = userInfoDAO.find(obj.getId());
		userInfo.setLastVisit(obj.getLastVisit());
		userInfo.setNumAttempt(obj.getNumAttempt());
		userInfo.setEnabled(obj.isEnabled());
		userInfoDAO.update(userInfo);
	}
	
	public void changePassword(UserInfo userInfo, String newPassword) {
		userInfo = find(userInfo.getId());
		Date now = new Date();
		userInfo.setPassword(newPassword);
		userInfo.setUpdateDate(now);
		userInfo.setUpdateUser(userInfo.getLoginId());
		userInfoDAO.update(userInfo);
		
		HistoryRecord historyRecord = new HistoryRecord();
		historyRecord.setAction(HistoryRecordActionEnum.CHANGE_PASS);
		historyRecord.setCreateDate(now);
		historyRecord.setCreateUser(userInfo.getLoginId());
		historyRecord.setStartTime(now);
		historyRecord.setUserInfo(userInfo);
		historyRecordService.save(historyRecord);
	}
	
	
}
